from PySide6.QtWidgets import QWidget,QFileDialog,QMessageBox,QTableWidgetItem,QMenu,QAbstractItemView,QHeaderView
from PySide6.QtCore import Qt
import os,shutil,pandas as pd

from views.salary.position.position.position import Ui_position
from views.salary.position.position.operationpositionView import OperationPositionView
from sqlalchemy.orm import Session
from settings.publicvar import engine
from views.person.model.person import PersonBaseInfo
from views.salary.model.salary import Position

class PositionView(QWidget,Ui_position):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.positiontable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.positiontable.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.positiontable.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
        self.positiontable.setContextMenuPolicy(Qt.CustomContextMenu)
        self.positiontable.customContextMenuRequested.connect(self.generate_menu)

        self.addposition.clicked.connect(self.addPositionFun)
        self.serearchbtn.clicked.connect(self.serearchFun)
        self.sereachedit.editingFinished.connect(self.serearchFun)
        self.downloadmodle.clicked.connect(self.downloadmodleFun)
        self.importbtn.clicked.connect(self.importdataFun)
        #
        self.load_table_data()

        # 菜单
    def generate_menu(self, pos):
        menu = QMenu()
        viewitem = menu.addAction('查看')
        changeitem = menu.addAction('修改')
        deletitem = menu.addAction('删除')
        action = menu.exec(self.positiontable.mapToGlobal(pos))
        posrow = self.positiontable.currentRow()
        columns = self.positiontable.columnCount()
        data = [self.positiontable.item(posrow, i).text() for i in range(columns)]
        if action == changeitem:
            changeposition = OperationPositionView('change', data)
            changeposition.exec()
        elif action == deletitem:
            delete = OperationPositionView('delete',data)
            delete.exec()
        elif action == viewitem:
            viewposition = OperationPositionView('view', data)
            viewposition.exec()
        self.load_table_data()

    # 添加单条数据
    def addPositionFun(self):
        addposition = OperationPositionView('add',False)
        addposition.exec()

    # 搜索数据
    def serearchFun(self):
        sereachdata = self.sereachedit.text().strip()
        if sereachdata == '':
            QMessageBox.critical(None, '错误', '搜索框不能为空！')
            self.load_table_data()
        else:
            with Session(engine) as session, session.begin():
                sereachName = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.name.like('%' + sereachdata + '%')).all()
                sereachIDcard = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.IDcard.like('%' + sereachdata + '%')).all()
                sereachiphone = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.iphone.like('%' + sereachdata + '%')).all()
                sereachData = sereachName + sereachIDcard + sereachiphone
                others = []
                if sereachData:
                    for personbase in sereachData:
                        for other in personbase.positions:
                            others.append(other)
                    # 数据处理和加载QTable表
                    self.setTableStructure(others)
                else:
                    QMessageBox.critical(None,'没有数据','你搜索数据不存在！')

    # 表格结构
    def setTableStructure(self,data):
        self.positiontable.setRowCount(len(data))
        for i,item in enumerate(data):
            idx = QTableWidgetItem(str(item.id))
            self.positiontable.setItem(i, 0, idx)
            name = QTableWidgetItem(item.personbase.name)
            self.positiontable.setItem(i, 1, name)
            acquisition_method = QTableWidgetItem(item.acquisition_method)
            self.positiontable.setItem(i, 2, acquisition_method)
            post_grade = QTableWidgetItem(str(item.post_grade))
            self.positiontable.setItem(i, 3, post_grade)
            acquisition_date = QTableWidgetItem(str(item.acquisition_date))
            self.positiontable.setItem(i, 4, acquisition_date)
            hire_date= QTableWidgetItem(str(item.hire_date))
            self.positiontable.setItem(i, 5, hire_date)
            execute_date = QTableWidgetItem(str(item.execute_date))
            self.positiontable.setItem(i, 6, execute_date)
            post_type = QTableWidgetItem(item.post_type)
            self.positiontable.setItem(i,7,post_type)
            mark = QTableWidgetItem(item.mark)
            self.positiontable.setItem(i, 8, mark)

    # 数据加载
    def load_table_data(self):
        with Session(engine) as session,session.begin():
            positions = session.query(Position).all()
            self.setTableStructure(positions)

    # 下载模板
    def downloadmodleFun(self):
        model_file_path = "state/model/岗位情况模板.xlsx"
        model_file_name = os.path.basename(model_file_path)
        save_path, _ = QFileDialog.getSaveFileName(self, '下载模板', model_file_name,
                                                   f"(*.{model_file_name.split('.')[-1]})")
        shutil.copy2(model_file_path, save_path)
        QMessageBox.information(None, '下载成功', '恭喜你下载成功！')

    # 导入数据
    def importdataFun(self):
        url, a = QFileDialog.getOpenFileUrl(self, '导入数据')
        try:
            data = pd.read_excel(url.toLocalFile(), sheet_name=0, header=1,
                                 names=['idx','name','IDcard','acquisition_method','post_grade','acquisition_date','hire_date','execute_date','post_type','mark'],
                                 dtype={'IDcard': str},
                                 parse_dates=['acquisition_date','hire_date','execute_date']).drop('idx', axis=1)
            data = data.where(data.notna(), '')
            data['acquisition_date'] = data['acquisition_date'].replace({pd.NaT: None})
            data['hire_date'] = data['hire_date'].replace({pd.NaT: None})
            data['execute_date'] = data['execute_date'].replace({pd.NaT: None})
            with Session(engine) as session, session.begin():
                query_exist_personbase_tem = session.query(PersonBaseInfo.IDcard,PersonBaseInfo.id).filter(
                    PersonBaseInfo.IDcard.in_(data.IDcard.to_list())).all()

                if query_exist_personbase_tem:
                    qury_exist_personbase = [tem[0] for tem in query_exist_personbase_tem]
                    qury_exist_personbase_id = pd.DataFrame(query_exist_personbase_tem).rename(
                        columns={'id': 'name_id'})
                    save_person = data[data['IDcard'].isin(qury_exist_personbase)]
                    positions = pd.merge(qury_exist_personbase_id, save_person, on='IDcard').drop(columns=['name', 'IDcard']).to_dict('records')
                    positions = [Position(**item) for item in positions ]
                    session.add_all(positions)
                    QMessageBox.information(None, '提示', '你导入成功%s条，失败%s条，明细如下！' % (len(positions), len(data) - len(positions)))
        except:
            QMessageBox.critical(None, '导入失败', '你没有选择文件！')
        self.load_table_data()